package org.openclinic.repository;

import java.util.Date;
import java.util.List;

import org.openclinic.domain.Appointment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public interface AppointmentRepository extends JpaRepository<Appointment, Long> {
	
	@Modifying
	@Transactional(propagation = Propagation.REQUIRED)
	@Query("UPDATE Appointment SET canceled = true WHERE appointmentId = ?1")
	void cancelByAppointmentId(long appointmentId);
	
	Appointment findByAppointmentId(long appointmentId);
	
	@Query("FROM Appointment WHERE professional_id = ?1 AND customer_id = ?2 AND startDate BETWEEN ?3 AND ?4 AND canceled = false")
	List<Appointment> find(long professionalId, long customerId, Date startDate, Date endDate);

	@Query("FROM Appointment a WHERE a.customer.id = ?1 AND a.startDate = ?2 AND canceled = false ORDER BY startDate")
	List<Appointment> findByCustomerAndDate(long customerId, Date startDate);
	
	List<Appointment> findByCustomerUserIdAndCanceled(long userId, boolean canceled);
	
	@Query("FROM Appointment a WHERE a.medicalSpecialty.id = ?1 AND a.healthProfessional.id = ?2 AND a.startDate BETWEEN ?3 AND ?4 AND fit = false AND canceled = false")
	List<Appointment> findByProfessionalSpecialty(long specialtyId, long professionalId, Date startDate, Date endDate);

	@Query("FROM Appointment a WHERE a.healthProfessional.id = ?1 AND a.startDate = ?2 AND canceled = false ORDER BY startDate")
	List<Appointment> findByProfessionalAndDate(long professionalId, Date startDate);
	
	@Query("FROM Appointment a WHERE a.healthProfessional.id = ?1 AND a.startDate BETWEEN ?2 AND ?3 AND canceled = false ORDER BY startDate")
	List<Appointment> findByProfessionalAndDate(long professionalId, Date startDate, Date endDate);
}
